//
//  AIDetailViewController.swift
//  AIImage
//
//  Created by deng on 2023/12/10.
//

import UIKit
import SnapKit
import Alamofire

class AIDetailViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    lazy var tableView:UITableView = {
        let tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        return tableView
    }()
    var detailVo = AISaveModel()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if #available(iOS 15.0, *) {
            let barAppearance = UINavigationBarAppearance.init()
            barAppearance.backgroundColor = .clear
            navigationController?.navigationBar.scrollEdgeAppearance = nil
            navigationController?.navigationBar.standardAppearance = barAppearance
        } else {
            navigationController?.navigationBar.barTintColor = .clear
            navigationController?.navigationBar.shadowImage = UIImage()
            navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        }
        navigationController?.navigationBar.isTranslucent = true
        navigationController?.navigationBar.tintColor = .clear
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if #available(iOS 11.0, *) {
            UIScrollView.appearance().contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        
        let leftBtn = UIButton()
        leftBtn.setImage(UIImage(named: "back_icon"), for: .normal)
        leftBtn.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: leftBtn)
        leftBtn.addTarget(self, action: #selector(goBack), for: .touchUpInside)

        // Do any additional setup after loading the view.
        let bgView = UIImageView.init(image: UIImage(named: "bg_icon"))
        bgView.frame = view.bounds
        bgView.isUserInteractionEnabled = true
        bgView.contentMode = .scaleAspectFill
        view.addSubview(bgView)
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(kNavigationH+10*DS.s)
        }
        tableView.register(cellType: AIDetailTopTableViewCell.self)
        tableView.register(cellType: AIDetailListTableViewCell.self)
    }
    
    @objc func goBack(){
        
        navigationController?.popViewController(animated: true)
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return detailVo.result?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row > 0{
            let cell: AIDetailListTableViewCell = tableView.dequeueReusableCell(for: indexPath)
            let vo = detailVo.result?[indexPath.row - 1] ?? ResultList()
            cell.setupData(vo: vo)
            cell.callBackBlock {[weak self] _ in
                
                self?.getDetailAPI(vo: vo)
            }
            return cell
        }
        let cell: AIDetailTopTableViewCell = tableView.dequeueReusableCell(for: indexPath)
        cell.setUpData(vo: detailVo)
        return cell
    }
    
    private func getDetailAPI(vo:ResultList){
        
        let loadingView = LoadingView(frame: CGRect(x: KScreenWidth/2-70*DS.s, y: KScreenHeight/2-50*DS.s, width: 140*DS.s, height: 100*DS.s), text: "AI正在获取中...")
        view.addSubview(loadingView)
        let url = "https://img-identify-qs-axrxhqrjus.cn-hangzhou.fcapp.run/detail?name=\(vo.name ?? "")"
        AF.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default).responseJSON { response in
            loadingView.stopLoading()
            switch response.result {
            case let .success(json):
                if let err = response.error {
                } else {
                    let dict = json
                    if let dic = dict as? NSDictionary {
                        let model = AIModel.deserialize(from: dic) ?? AIModel()
                        let aiVC = AIQuestionViewController()
                        model.name = vo.name ?? ""
                        aiVC.detailM = model
                        aiVC.fatherM = self.detailVo
                        self.navigationController?.pushViewController(aiVC, animated: true)
                    }
                }
            case let .failure(errorD):
                print("出错啦:\(errorD)")
            }
        }
    }
}
    
